package com.tencent.wxcloudrun.common.component;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tencent.wxcloudrun.common.utils.HttpUtils;
import com.tencent.wxcloudrun.common.utils.StringUtils;
import com.tencent.wxcloudrun.common.utils.WeChatAccessResult;
import com.tencent.wxcloudrun.project.entity.Order;
import com.tencent.wxcloudrun.project.entity.TableNum;
import com.tencent.wxcloudrun.project.entity.query.WeChatQueryObject;
import com.tencent.wxcloudrun.project.mapper.TableNumMapper;
import com.tencent.wxcloudrun.project.service.TableNumService;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.*;

import org.apache.http.HttpResponse;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class WeChatCommon {
    @Value("${files.upload.path}")
    private String fileUploadPath;
    @Value("${wechat.mini.appid}")
    private String appId ;
    @Value("${wechat.mini.secret}")
    private String secret;
    @Autowired
    private TableNumMapper tableNumMapper;

    /**
     * 获取微信access_token
     */
    public WeChatAccessResult returnAccessToken(){
        if (StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(secret)){
            String url ="https://api.weixin.qq.com/cgi-bin/token";
            //根据code 换取access token
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type","client_credential");
            params.put("appid",appId);
            params.put("secret",secret);
            String response = HttpUtil.get(url,params);
            WeChatAccessResult weChatAccessResult = JSONObject.parseObject(response, WeChatAccessResult.class);
            return weChatAccessResult;
        }
        return  null;
    }
    public String getOpenid(String code) throws IOException {
        String openId = "";
        try{//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            String url ="https://api.weixin.qq.com/sns/jscode2session";
            Map<String, Object> params = new HashMap<>();
            params.put("appid",appId);
            params.put("secret",secret);
            params.put("js_code",code);
            params.put("grant_type","authorization_code");
            openId = HttpUtil.get(url,params);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return openId;
    }
    /**
     * @param weChatQueryObject 查询参数
     * @return
     * @throws IOException
     */
    public String getWxCode(WeChatQueryObject weChatQueryObject){
        WeChatAccessResult weChatAccessResult = returnAccessToken();
        if (weChatAccessResult!=null && StringUtils.isNotEmpty(weChatAccessResult.getAccessToken())
                && weChatQueryObject !=null
        ){
//            String resourceUrl = fileUploadPath;
            String resourceUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/files/";
            String uuid= IdUtil.fastSimpleUUID();
            String name = uuid+".png";
            String  queryURL ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+weChatAccessResult.getAccessToken();
            //请求接口地址
            RestTemplate restTemplate = new RestTemplate();
            //设置头部
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);
            TableNum tableNum=new TableNum();
            tableNum.setName(weChatQueryObject.getName());
            tableNum.setImg("/files/"+name);
            //设置body
            //对应请求参数见微信开放文档：https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("path", "pages/index/index");
            requestBody.put("width",weChatQueryObject.getWidth());
            if(weChatQueryObject.getScene()!=null){
                requestBody.put("scene",weChatQueryObject.getScene());
            }else{
                tableNumMapper.insert(tableNum);
                requestBody.put("scene",tableNum.getId());
            }
            requestBody.put("auto_color",weChatQueryObject.isAuto_color());
            requestBody.put("is_hyaline",weChatQueryObject.is_hyaline());
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
            byte[] res=restTemplate.postForObject(queryURL, requestEntity, byte[].class);
            //将获取到的buffer流存储到本地图片
            File f = new File(resourceUrl+name);
            try {
                if(res.length<=500) {//如果byte字节流小于500，说明返回的是err错误码而非buffer
                    return new String(res);
                }else {
                    BufferedOutputStream out = new BufferedOutputStream(
                            new FileOutputStream(f));
                    out.write(res);
                    out.flush();
                    out.close();
                }
            }catch(Exception e) {
                e.printStackTrace();
                return "IO Error";
            }
            return "/files/"+name;
        }
        return null;
    }
    public String sendSubscribe1(Order order){
        WeChatAccessResult weChatAccessResult = returnAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + weChatAccessResult.getAccessToken();
        Map<String,Object> jsonMap = new HashMap<>();
        jsonMap.put("touser",order.getCustomId());
        jsonMap.put("template_id","lxQ2Z5RxGg5F5pmSEFxNd1isk0hzYdCsopeYX1T3ung");
        jsonMap.put("page","pages/orderDetailed/index?orderId="+order.getId());
        jsonMap.put("miniprogram_state","trial");
        Map<String,Object> data = new HashMap<>();
        data.put("character_string8", getDataMap(order.getId().toString()));
        data.put("phrase9", getDataMap("已受理"));
        data.put("date3", getDataMap(getStringDate(order.getTime())));
        data.put("time10", getDataMap(getStringDate(new Date())));
        data.put("thing11", getDataMap(order.getRemarks()));
        jsonMap.put("data",data);
        JSONObject object = new JSONObject(jsonMap);
        String json = object.toString();
        String response=HttpUtils.HttpPostWithJson(url,json);
        return response;
    }
    public String sendSubscribe2(Order order){
        WeChatAccessResult weChatAccessResult = returnAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + weChatAccessResult.getAccessToken();
        Map<String,Object> jsonMap = new HashMap<>();
        jsonMap.put("touser",order.getCustomId());
        jsonMap.put("template_id","uUAljnS5sanQ-qyiiurK0hSwPhIsL8dv8xytTnKEWJo");
        jsonMap.put("page","pages/orderDetailed/index?orderId="+order.getId());
        jsonMap.put("miniprogram_state","trial");
        Map<String,Object> data = new HashMap<>();
        data.put("character_string5", getDataMap(order.getId().toString()));
        data.put("date2", getDataMap(getStringDate(order.getTime())));
        data.put("amount9", getDataMap(order.getMoney().toString()+"元"));
        data.put("phrase10", getDataMap("已完成"));
        data.put("time3", getDataMap(getStringDate(new Date())));
        jsonMap.put("data",data);
        JSONObject object = new JSONObject(jsonMap);
        String json = object.toString();
        String response=HttpUtils.HttpPostWithJson(url,json);
        return response;
    }
    public static Map<String, String> getDataMap(String msg){
        Map<String, String> map = new HashMap<>();
        map.put("value", msg);
        return map;
    }
    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate(Date date) {
        Date currentTime = date;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
}
